<template>
  <FullPageModal
    v-model:visible="modelVisible"
    title="新增设备"
    :custom-footer="true"
    @ok="ok"
    @cancel="cancel"
    @open="open"
  >
    <div ref="content" class="w-px-1 mx-auto px-32">
      <a-steps :current="currentStep" :initial="0" status="wait">
        <a-step status="process">
          <template #icon> </template>
          <template #title>
            <div class="flex flex-col">
              <p
                :class="
                  currentStep === 0 ? 'text-color-active' : feedbackMsg[0] ? ' text-color-secondary' : 'text-color-main'
                "
                class="m-0 text-xl font-semibold"
                >基本信息</p
              >
              <p class="m-0 text-color-secondary text-sm">{{ feedbackMsg[0] || "已完成" }}</p>
            </div>
          </template>
        </a-step>
        <a-step status="process">
          <template #icon> </template>
          <template #title>
            <div class="flex flex-col">
              <p
                :class="
                  currentStep === 1 ? 'text-color-active' : feedbackMsg[1] ? ' text-color-secondary' : 'text-color-main'
                "
                class="m-0 text-xl font-semibold"
                >接入信息</p
              >
              <p class="m-0 text-color-secondary text-sm">{{ feedbackMsg[1] || "已完成" }}</p>
            </div>
          </template>
        </a-step>
        <a-step status="process">
          <template #icon> </template>
          <template #title>
            <div class="flex flex-col">
              <p
                :class="currentStep === 2 ? 'text-color-active' : 'text-color-secondary'"
                class="m-0 text-xl font-semibold"
                >其他信息</p
              >
              <p class="m-0 text-color-secondary text-sm">无必填项</p>
            </div>
          </template>
        </a-step>
      </a-steps>
      <div class="mt-8">
        <DynamicForm
          v-show="currentStep === 0"
          ref="equipmentIns"
          :model="baseInfoModel"
          :model-form-setting="baseInfoFormSetting"
          :force-column="true"
        />
        <DynamicForm
          v-show="currentStep === 1"
          ref="netInfoIns"
          :model="netInfoModel"
          :model-form-setting="netInfoFormSetting"
          :force-column="true"
        />
        <DynamicForm
          v-show="currentStep === 2"
          ref="equipmentOtherIns"
          :model="otherInfoModel"
          :model-form-setting="otherInfoFormSetting"
          :force-column="true"
        />
        <panel v-show="currentStep === 2" title="自定义属性">
          <a-form ref="equipmentAttrForm" name="attr_form" :model="customeAttrForm" layout="vertical">
            <div
              v-for="(customerAttr, index) in customeAttrForm.customeAttr"
              :key="index"
              class="flex flex-row items-center"
            >
              <a-form-item
                class="mr-7 flex-1"
                :name="['customeAttr', index, 'customLabel']"
                label="属性名称"
                :rules="{
                  message: '请输入自定义属性名称',
                }"
              >
                <a-input v-model:value="customerAttr.customLabel" :maxlength="32" />
              </a-form-item>
              <a-form-item
                class="mr-7 flex-1"
                label="属性内容"
                :name="['customeAttr', index, 'customValue']"
                :rules="{
                  message: '请输入自定义属性内容',
                }"
              >
                <a-input v-model:value="customerAttr.customValue" :maxlength="32" />
              </a-form-item>
              <div>
                <delete-outlined class="text-2xl !text-color-danger" @click="removeAttr(customerAttr)" />
              </div>
            </div>
            <a-form-item class="mb-0">
              <a-button type="link" class="!p-0" @click="addAttr">
                <template #icon>
                  <Icon type="icon-tianjia" />
                </template>
                添加自定义属性
              </a-button>
            </a-form-item>
          </a-form>
        </panel>
      </div>
    </div>
    <template #footer>
      <div class="flex flex-row items-center justify-end mt-4">
        <a-button @click="cancel">取消</a-button>
        <a-button v-show="currentStep !== 0" @click="preFn()">返回</a-button>
        <a-button v-show="currentStep !== 2" type="primary" @click="nextFn()">继续</a-button>
        <a-button v-show="currentStep === 2" @click="ok(false)">确定</a-button>
        <a-button v-show="currentStep === 2" type="primary" @click="ok(true)">确认并绑定点位</a-button>
      </div>
    </template>
    <a-modal
      v-model:visible="selectEquipmentTypeVisible"
      title="选择设备机型"
      width="900px"
      height="600px"
      class="dispatchContainer"
      @ok="handleSelectEquipmentType"
    >
      <div ref="content" class="mx-auto">
        <EquipmentTypeSelect
          ref="equipmentTypeIns"
          v-model:value="selectedEquipmentTypeId"
          :single-select="true"
          :is-enterprise="true"
          placeholder="搜索设备机型"
        />
      </div>
    </a-modal>
    <SelectOrganizationUserModal v-model:visible="chooseUserVisible" @ok="handleChooseUserOkFn" />
    <SetEquipmentFunction
      v-model:visible="equipmentFuncVisible"
      v-model:options="curEquipmentType"
      :is-enterprise="true"
      :is-view="true"
      :get-container="projectId ? getContainer : null"
    />
    <GatewayBindModal v-model:visible="gatewayBindVisible" :options="curEquipmentOption" />
  </FullPageModal>
</template>
<script lang="ts" setup>
import { CustomAttributesItem } from "/@/api/aiot/projectManage/models";
import { useI18n } from "/@/locales/useI18n";
import GatewayBindModal from "./GatewayBindModal.vue";
import { nextTick, ref, shallowRef, watch, h, onMounted } from "vue";
import FullPageModal from "/@/components/FullPageModal.vue";
import { CURDAction, FormItemComponentType, FormItemData } from "/@/components/CURDDialog/models";
import {
  ParEquipmentDetail,
  EquipmentTypeItem,
  EquipmentFunctionModalOptions,
  GatewayModalPropsOptions,
} from "/@/api/aiot/equipment/models";
import { addEquipment } from "/@/api/aiot/equipment";
import { brandsPage } from "/@/api/aiot/brand";
import { projectsPage } from "/@/api/aiot/projectManage";
import SelectInput from "/@/components/common/SelectInput.vue";
import EquipmentTypeSelect from "./EquipmentTypeSelect.vue";
import { gatewayPage } from "/@/api/aiot/gateway";
import { message } from "ant-design-vue";
import { PatternKey } from "/@/utils/verify";
import { DeleteOutlined } from "@ant-design/icons-vue";
import SelectOrganizationUserModal from "/@/views/aiot/enterprise/ProjectManage/SelectOrganizationUserModal.vue";
import EquipmentTypeSelectRow from "./EquipmentTypeSelectRow.vue";
import { pageEquipmentCategoryEnter } from "/@/api/aiot/deviceType";
const props = withDefaults(
  defineProps<{
    visible: boolean;
    projectId?: string;
    showMember?: boolean;
  }>(),
  {
    showMember: true,
  }
);
const { t } = useI18n();
const curEquipmentType = ref<EquipmentFunctionModalOptions>({
  equipmentTypeId: "",
  equipmentTypeName: "",
  defaultEquipmentTypeId: "",
});
const chooseUserVisible = ref(false);
const curEquipmentOption = ref<GatewayModalPropsOptions>({
  equipmentId: "",
  equipmentName: "",
  gatewayId: "",
  gatewayTypeId: "",
  equipmentTypeId: "",
});
const gatewayBindVisible = ref(false);
const equipmentFuncVisible = ref(false);
const equipmentAttrForm = ref();
const equipmentIns = ref();
const equipmentTypeIns = ref();
const equipmentOtherIns = ref();
const netInfoIns = ref();
const selectedEquipmentTypeId = ref<string[]>([]);
const emits = defineEmits(["create", "update:visible", "successFn", "update:projectDetail", "update:projectId"]);
const currentStep = ref<number>(0);
const feedbackMsg = ref<string[]>(["5项必填未填", "3项必填未填"]);
const modelVisible = ref<boolean>(false);
const selectEquipmentTypeVisible = ref<boolean>(false);
const baseInfoModel = ref<ParEquipmentDetail>({
  equipmentName: "",
  equipmentNo: "",
  projectId: props.projectId || "",
  equipmentCategoryId: "",
  equipmentTypeName: "",
  brandId: "",
  location: "",
  equipmentTags: "",
  equipmentTypeId: "",
});
const baseInfoFormSetting: FormItemData[] = [
  {
    key: "_subTitle",
    beforeKey: "equipmentName",
    subTitle: "基本信息",
  },
  {
    key: "equipmentName",
    label: "设备名称",
    max: 32,
    required: true,
  },
  {
    key: "equipmentNo",
    label: "设备编号",
    labelDes: "支持大小写字母、数字和下划线",
    pattern: PatternKey.code,
    max: 32,
    required: true,
  },
  {
    key: "projectId",
    label: "所属项目",
    required: true,
    type: FormItemComponentType.SELECT,
    async getData() {
      const data = await projectsPage();
      return data
        ? data?.records.map((el) => ({
            label: el.projectName,
            value: el.projectId,
          }))
        : [];
    },
    props: {
      options: [],
      getPopupContainer(node) {
        return node.parentNode;
      },
    },
  },
  {
    key: "equipmentCategoryId",
    label: "设备类别",
    type: FormItemComponentType.TREESELECT,
    getData: async () => {
      let equipmentCategoryData = (await pageEquipmentCategoryEnter())?.records || [];
      return equipmentCategoryData;
    },
    props: {
      fieldNames: { label: "equipmentCategoryName", value: "equipmentCategoryId" },
    },
  },
  {
    label: "设备机型",
    key: "equipmentTypeName",
    required: true,
    props: {
      placeholder: "请选择设备机型",
    },

    customComponent: h(EquipmentTypeSelectRow, {
      onClick() {
        selectEquipmentTypeVisible.value = true;
        nextTick(() => {
          equipmentTypeIns.value.reset();
        });
      },
      onCheck() {
        curEquipmentType.value = {
          equipmentTypeId: baseInfoModel.value.equipmentTypeId || "",
          equipmentTypeName: baseInfoModel.value.equipmentTypeName || "",
          defaultEquipmentTypeId: "1",
        };
        equipmentFuncVisible.value = true;
      },
    }),
  },
  // {
  //   label: "设备类型",
  //   key: "equipmentTypeName",
  //   required: true,
  //   props: {
  //     placeholder: "请选择设备类型",
  //   },
  //   customComponent: h(SelectInput, {
  //     onClick() {
  //       selectEquipmentTypeVisible.value = true;
  //       nextTick(() => {
  //         equipmentTypeIns.value.reset();
  //       });
  //     },
  //   }),
  // },
  {
    key: "brandId",
    label: "设备品牌",
    required: true,
    type: FormItemComponentType.SELECT,
    async getData() {
      const data = await brandsPage();
      return data
        ? data.records.map((el) => ({
            label: el.brandChineseName,
            value: el.brandId,
          }))
        : [];
    },
    props: {
      options: [],
      getPopupContainer(node) {
        return node.parentNode;
      },
    },
  },
  {
    key: "location",
    label: "安装位置",
    max: 32,
    labelDes: "建议按照“园区-建筑-楼层录入”",
  },
  {
    key: "equipmentTags",
    label: "设备标签",
    type: FormItemComponentType.SELECT,
    props: {
      options: [
        { label: "重点设备", value: "important" },
        { label: "普通设备", value: "normal" },
      ],
    },
  },
  {
    key: "equipmentTypeId",
    hide: true,
  },
];
const otherInfoModel = ref<ParEquipmentDetail>({
  equipmentPhotos: [],
  nameplateInfo: [],
  serialNumber: "",
  manufacturer: "",
  specification: "",
  chargePerson: "",
  useDate: "",
  descriptions: "",
  chargePersonId: "",
});
const otherInfoFormSetting: FormItemData[] = [
  {
    key: "_subTitle",
    beforeKey: "equipmentPhotos",
    subTitle: "其他信息",
  },
  {
    key: "equipmentPhotos",
    label: "设备图片",
    labelDes: "建议尺寸1600像素*900像素，仅支持jpg/jpeg/png/gif格式，若不设置则系统默认",
    type: FormItemComponentType.IMGUPLOAD,
    props: {
      max: 6,
    },
  },
  {
    key: "nameplateInfo",
    label: "铭牌图片",
    labelDes: "支持jpg/jpeg/png/gif格式",
    type: FormItemComponentType.IMGUPLOAD,
    props: {
      max: 6,
    },
  },
  {
    key: "serialNumber",
    label: "设备序列号",
    max: 32,
  },
  {
    key: "manufacturer",
    label: "生产厂商",
    max: 32,
  },
  {
    key: "specification",
    label: "规格型号",
    max: 32,
  },
  {
    key: "chargePerson",
    label: "设备责任人",
    customComponent: h(SelectInput, {
      onClick() {
        chooseUserVisible.value = true;
      },
    }),
  },
  {
    key: "chargePersonId",
    hide: true,
  },
  {
    key: "useDate",
    label: "投入使用时间",
    type: FormItemComponentType.DATEPICKER,
    props: {
      class: "w-full",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
    },
  },
  {
    key: "descriptions",
    label: "设备简介",
    max: 200,
  },
];
const netInfoModel = ref<ParEquipmentDetail>({
  gatewayId: "",
  connectType: "0",
  slavType: "0",
  slaveId: 0,
});
const netInfoFormSetting: FormItemData[] = [
  {
    key: "_subTitle",
    beforeKey: "gatewayId",
    subTitle: "接入信息",
  },

  {
    key: "gatewayId",
    label: "所属网关",
    required: true,
    type: FormItemComponentType.SELECT,
    async getData({ params }) {
      if (!params) return [];
      const data = await gatewayPage({ size: 999, current: 1, model: { projectId: params || "" } });
      return data
        ? data.records.map((el) => ({
            label: el.gatewayName,
            value: el.gatewayId,
          }))
        : [];
    },
    props: {
      options: [],
      getPopupContainer(node) {
        return node.parentNode;
      },
    },
  },
  {
    key: "connectType",
    label: "接入方式",
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: [
        { label: "默认", value: "0" },
        { label: "modbus", value: "1" },
      ],
    },
  },
  {
    key: "slavType",
    label: "主从模式",
    required: true,
    type: FormItemComponentType.SELECT,
    hide: true,
    props: {
      options: [
        { label: "主机", value: "0" },
        { label: "从机", value: "1" },
      ],
    },
  },
  {
    key: "slaveId",
    label: "从机地址",
    required: true,
    labelDes: "取值范围1-255",
    pattern: PatternKey.maxNumber255,
    props: {
      type: "number",
    },
    hide: true,
  },
];
function open(isFirstOpen) {
  if (isFirstOpen) {
    //第一次打开 加载数据
    nextTick(() => {
      equipmentIns.value?.initFormItemComponentData();
    });
  } else {
    //之后每次打开 重置
    reset();
  }
}
watch(
  () => props.visible,
  (v) => {
    modelVisible.value = v;
    if (!v) {
      reset();
    } else {
      if (props.projectId) {
        baseInfoFormSetting[3].props.disabled = true;
        nextTick(() => {
          netInfoIns.value?.reloadFormItemComponentData("gatewayId", props.projectId);
        });
      }
    }
  }
);
watch(modelVisible, (v) => {
  emits("update:visible", v);
});
watch(
  () => baseInfoModel.value.projectId,
  (v) => {
    netInfoModel.value.gatewayId = "";
    if (v) {
      netInfoIns.value?.reloadFormItemComponentData("gatewayId", v);
    }
  },
  { immediate: true }
);
onMounted(() => {});
watch(
  () => props.projectId,
  (v) => {
    nextTick(() => {
      netInfoModel.value.gatewayId = "";
      if (v) {
        netInfoIns.value?.reloadFormItemComponentData("gatewayId", v);
      }
    });
  },
  { immediate: true }
);
watch(
  () => netInfoModel.value.slavType,
  (v) => {
    netInfoIns.value?.toggleField("slaveId", v === "0");
    netInfoModel.value.slaveId = 1;
  },
  { immediate: true }
);
watch(
  () => netInfoModel.value.connectType,
  (v) => {
    netInfoModel.value.slaveId = 0;
    netInfoModel.value.slavType = "0";
    netInfoIns.value?.toggleField("slavType", v !== "1");
    netInfoIns.value?.toggleField("slaveId", v !== "1" || netInfoModel.value.slavType !== "1");
  },
  { immediate: true }
);
function reset() {
  equipmentIns.value?.initFormItemComponentData();
  equipmentOtherIns.value?.initFormItemComponentData();
  netInfoIns.value?.initFormItemComponentData();
  // 初始化验证
  equipmentIns.value?.resetFields();
  equipmentOtherIns.value?.resetFields();
  netInfoIns.value?.resetFields();
  otherInfoModel.value.chargePerson = "";
  otherInfoModel.value.chargePersonId = "";
  currentStep.value = 0;
  feedbackMsg.value = ["5项必填未填", "3项必填未填"];
  customeAttrForm.value = {
    customeAttr: [],
  };
}
/**
 * ok cancel
 */
const content = shallowRef<HTMLDivElement>();
async function ok(isContinue) {
  let obj = Object.assign({}, baseInfoModel.value);
  obj = Object.assign(obj, otherInfoModel.value);
  obj = Object.assign(obj, netInfoModel.value);
  obj.additionalinfo = JSON.stringify(customeAttrForm.value.customeAttr);
  let notOk = false;
  for (let item of feedbackMsg.value) {
    if (item) {
      notOk = true;
    }
  }
  if (obj.connectType === "0") {
    obj.slaveId = null;
  }
  if (!notOk) {
    let req = await addEquipment(obj);
    if (req) {
      message.success("操作成功");
      emits("successFn");
      if (isContinue) {
        // open();
        currentStep.value = 0;
        feedbackMsg.value = ["5项必填未填", "3项必填未填"];
        modelVisible.value = false;
        curEquipmentOption.value = {
          equipmentId: req.equipmentId,
          equipmentName: obj.equipmentName,
          gatewayId: obj.gatewayId || "",
          gatewayTypeId: obj.gatewayTypeId || "",
          equipmentTypeId: obj.equipmentTypeId,
        };
        gatewayBindVisible.value = true;
        // reset();
      } else {
        modelVisible.value = false;
      }
    }
  } else {
    message.warning("请填写完整信息再做此操作");
  }
}
function cancel() {
  emits("update:visible", false);
}
const modelIns = [equipmentIns, netInfoIns];
function nextFn() {
  modelIns[currentStep.value].value
    ?.validate()
    .then(async (model) => {
      feedbackMsg.value[currentStep.value - 1] = "";
    })
    .catch((err) => {
      feedbackMsg.value[currentStep.value - 1] = err.errorFields.length + "项必填未填";
    });
  currentStep.value > 2 ? null : (currentStep.value = currentStep.value + 1);
}
function preFn() {
  currentStep.value > 0 ? (currentStep.value = currentStep.value - 1) : null;
}
const selectedEquipmentType = ref<EquipmentTypeItem[]>([]);
function handleSelectEquipmentType() {
  selectedEquipmentType.value = equipmentTypeIns.value.getSelecedEquipmentType();
  baseInfoModel.value.equipmentTypeName = selectedEquipmentType.value[0].equipmentTypeName;
  baseInfoModel.value.equipmentTypeId = selectedEquipmentType.value[0].equipmentTypeId;
  selectEquipmentTypeVisible.value = false;
}
function handleChooseUserOkFn(selectUser) {
  if (selectUser.length <= 0) {
    message.warning("请选择用户");
    return;
  } else {
    otherInfoModel.value.chargePerson = selectUser[0].userName;
    otherInfoModel.value.chargePersonId = selectUser[0].userId;
  }
}
// 自定义属性
const customeAttrForm = ref<{ customeAttr: CustomAttributesItem[] }>({
  customeAttr: [],
});
function removeAttr(item: CustomAttributesItem) {
  let index = customeAttrForm.value.customeAttr.indexOf(item);
  if (index !== -1) {
    customeAttrForm.value.customeAttr.splice(index, 1);
  }
}
function addAttr() {
  if (customeAttrForm.value.customeAttr && customeAttrForm.value.customeAttr.length === 10) {
    message.warning("最多只能添加10条自定义属性");
    return;
  }
  customeAttrForm.value.customeAttr.push({
    customLabel: undefined,
    customValue: undefined,
  });
}
function getContainer() {
  return document.getElementById("root");
}
</script>
